<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType, OrderType } from '@/enum'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()

// 总的消息数组
const list = ref<Message[]>([])

// 1. 建立socket连接
let socket: Socket
onMounted(() => {
  // 1.1 创建socket实例
  // socket服务器的地址, {auth:{token: xxx}, query:{orderId:xxx}}
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 1.2 监听连接成功
  socket.on('connect', () => {
    // 1.2.0 清空聊天记录
    list.value = []
    // 1.2.1 接收默认聊天记录
    socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
      // 1.2.2 把消息处理成普通的消息列表
      const arr: Message[] = []
      data.forEach((item, i) => {
        // 设置获取上一个分组聊天记录的时间
        if (i === 0) time.value = item.createTime
        // 1.2.3 把时间创出一条消息
        arr.push({
          id: item.createTime,
          msgType: MsgType.Notify,
          createTime: item.createTime,
          msg: {
            content: item.createTime
          },
          noScroll: initialMsg.value === false
        })
        // 1.2.4 把剩余的消息放入数组
        // arr.push(...item.items)
        item.items.forEach((m) => {
          arr.push({ ...m, noScroll: initialMsg.value === false })
        })
      })
      // 1.2.5 往总的消息数组中合并
      list.value.unshift(...arr)

      // -----------------------
      // 1.2.6 关闭刷新效果
      loading.value = false
      // 1.2.7 提示用户没有数据了
      if (data.length === 0) {
        return showToast('没有更多聊天记录了...')
      }
      // 1.2.8 判断是否是初始获取聊天记录
      if (initialMsg.value) {
        nextTick(() => {
          // 滚动到最底部
          window.scrollTo(0, document.body.scrollHeight)
          // 修改记录第一次的值
          initialMsg.value = false
          // 标志消息已读
          socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        })
      }
    })
  })

  // 1.3 监听错误消息
  socket.on('error', (error) => {
    console.log('连接出现错误', error)
  })

  // 1.4 监听关闭连接
  socket.on('disconnect', () => {
    console.log('连接关闭')
  })
})

onUnmounted(() => {
  // 关闭socket连接
  socket.close()
})

// 2. 获取问诊订单详情
const consult = ref<ConsultOrderItem>()
onMounted(async () => {
  // 2.1 初始化时获取订单详情
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data

  // 2.2 订单状态发生改变时, 要重新获取订单详情
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
})

// 3. 发送消息
// 3.1 发送文字消息
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

// 3.2 发送图片消息
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

onMounted(() => {
  // 接收服务器给回来的数据消息
  socket.on('receiveChatMsg', async (msg: Message) => {
    // 1. 把消息对象放入list数组
    list.value.push(msg)

    // 2. 让聊天列表滚动到最底部(在下一个宏任务滚动)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)

    // 3. 标志消息已读
    socket.emit('updateMsgStatus', msg.id)
  })
})

// 4. 下拉加载
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const initialMsg = ref(true) // 记录是否是第一次加载聊天记录
const onRefresh = () => {
  // 4.1 向socket服务端发送数据
  // 参数：pageSize: number, lastTime: string, orderId: string
  // lastTime: string 当前分组第一条消息的时间 YYYY-MM-DD HH:mm:ss
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 5. 评分
provide('consult', consult)

// 修改评分数据对象
const completeEva = (score?: number) => {
  // 1. 找到评分的数据对象
  const item = list.value.find((obj) => obj.msgType === MsgType.CardEvaForm)
  // 2. 如果找到, 则添加和修改对应属性
  if (item) {
    // 修改消息类型
    item.msgType = MsgType.CardEva
    // 添加消息对象
    item.msg.evaluateDoc = { score }
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <!-- 问诊室状态 -->
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <!-- 问诊室消息 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <!-- 问诊室操作栏 -->
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
